#include <iostream>
#include <unistd.h>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <cstring>
#include <sys/types.h>
#include <sys/wait.h>

using namespace std;

void Write(int wfd)
{
    string s = "I am child";
    pid_t id = getpid();
    int number = 0;
    char buf[1024];
    while (1)
    {
        // buf[0] = 0;//清空字符串
        // snprintf(buf, sizeof(buf), "%s-%d-%d", s.c_str(), id, number++);

        // write(wfd, buf, strlen(buf));
        // sleep(1);


        //如果写端不写了，那么读端就会读到0，不会阻塞，表示读到了文件（pipe）末尾
        sleep(1);
        char c = 'x';
        write(wfd, &c, 1);
        number++;
        if(number >= 5) break;

    }
}


void Read(int rfd)
{

    char buffer[1024];

    while(1)
    {
        buffer[0] = 0;
        ssize_t s = read(rfd, buffer, sizeof(buffer));
        if(s > 0)
        {
            buffer[s] = 0;
            cout << "father["<< getpid() <<"] receive message: " << buffer << endl;
        }
        else if(s == 0)
        {
            cout << "read done" << endl;
            break;
        }
        else break;
    }

    sleep(5);
}

int main()
{
    
    int pipefd[2] = {0};
    //建立管道
    int ret = pipe(pipefd);

    if(ret < 0) return 1;

    //cout << pipefd[0] << pipefd[1] << endl;

    pid_t id = fork();
    if(id < 0)
    {
        perror("fork");
    }
    else if(id == 0)
    {
        //child
        //关闭读
        close(pipefd[0]);

        Write(pipefd[1]);

        close(pipefd[1]);
        exit(0);
    }

    //father
    //关闭写
    close(pipefd[1]);

    Read(pipefd[0]);

    pid_t r = waitpid(id, nullptr, 0);
    if(r < 0)
    {
        cout << "wait failed" << endl;
    }
    close(pipefd[0]);
    return 0;
}